﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Collections;
using GDoc.Domain;

namespace GDoc.Data.Sql
{
    public class RepositoryBase<T> : IRepositoryBase<T>
        where T : BaseEntity
    {
        public virtual UnitOfWork UnitOfWork { get; set; }

        public virtual DbSet<T> Set { get; set; }

        public virtual T SaveOrUpdate(T entity)
        {
            if (entity.Id == default(long))
            {
                T savedEntity = Set.Add(entity);
                UnitOfWork.Context.SaveChanges();

                return savedEntity;
            }
            else
            {
                UnitOfWork.Context.Entry(entity).State = System.Data.EntityState.Modified;
                UnitOfWork.Context.SaveChanges();

                return entity;
            }
        }

        public virtual T GetById(long id)
        {
            return Set.Where(a => a.Id.Equals(id)).SingleOrDefault();
        }

        public virtual IQueryable<T> GetAll()
        {
            return Set;
        }

        public virtual void Remove(T entity)
        {
            Set.Remove(entity);
            UnitOfWork.Context.SaveChanges();
        }

    }
}
